<template>
  <div class="container mx-auto px-4 py-6">
    <AppHeader/>
    <main class="space-y-6">
      <!-- 服务器控制面板 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="bg-gradient-to-r from-blue-50 to-blue-100 px-6 py-4">
          <h2 class="text-xl font-bold text-gray-700">MES 模拟服务器控制</h2>
        </div>
        <div class="p-6">
          <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-2">
              <span class="w-3 h-3 rounded-full"
                    :class="serverStatus.running ? 'bg-green-400 animate-pulse' : 'bg-red-400'"></span>
              <span class="text-gray-600">{{ serverStatus.running ? '运行中' : '已停止' }}</span>
            </div>
            <div class="text-gray-500 text-sm" v-if="serverStatus.running">
              端口: {{ serverStatus.port }}
            </div>
            <div class="ml-auto flex space-x-3">
              <button @click="startServer"
                      :disabled="serverStatus.running || isProcessing"
                      class="px-4 py-2 bg-emerald-100 text-emerald-700 rounded-lg hover:bg-emerald-200 
                             disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                <i class="fas fa-play mr-2"></i>启动服务器
              </button>
              <button @click="stopServer"
                      :disabled="!serverStatus.running || isProcessing"
                      class="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 
                             disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                <i class="fas fa-stop mr-2"></i>停止服务器
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 响应配置面板 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="bg-gradient-to-r from-purple-50 to-purple-100 px-6 py-4">
          <h2 class="text-xl font-bold text-gray-700">响应配置</h2>
        </div>
        <div class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-4">
              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">响应延迟 (毫秒)</label>
                <input type="number" v-model.number="config.delay"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md"/>
              </div>
              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">默认响应状态</label>
                <select v-model="config.defaultResult"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md">
                  <option value="PASS">PASS</option>
                  <option value="FAIL">FAIL</option>
                </select>
              </div>
            </div>
            <div class="space-y-4">
              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">错误序列号模式</label>
                <input type="text" v-model="config.errorPattern"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md"
                       placeholder="包含此文本的SN将返回FAIL"/>
              </div>
              <div class="mt-6">
                <button @click="saveConfig"
                        class="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors">
                  <i class="fas fa-save mr-2"></i>保存配置
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 请求日志面板 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="bg-gradient-to-r from-amber-50 to-amber-100 px-6 py-4">
          <div class="flex justify-between items-center">
            <h2 class="text-xl font-bold text-gray-700">请求日志</h2>
            <button @click="clearLogs"
                    class="px-3 py-1 text-sm bg-amber-200 text-amber-700 rounded-lg hover:bg-amber-300 transition-colors">
              清除日志
            </button>
          </div>
        </div>
        <div class="p-6">
          <div v-if="logs.length === 0" class="text-center text-gray-500 py-8">
            暂无请求日志
          </div>
          <div v-else class="space-y-4 max-h-96 overflow-y-auto">
            <div v-for="(log, index) in logs" :key="index"
                 class="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
              <div class="flex justify-between items-start mb-2">
                <div class="text-sm font-medium text-gray-700">
                  {{ log.timestamp }}
                </div>
                <div class="text-xs px-2 py-1 rounded-full"
                     :class="log.response.Result === 'PASS' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'">
                  {{ log.response.Result }}
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <div class="text-xs font-medium text-gray-500 mb-1">请求数据:</div>
                  <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto">{{
                      JSON.stringify(log.request, null, 2)
                    }}</pre>
                </div>
                <div>
                  <div class="text-xs font-medium text-gray-500 mb-1">响应数据:</div>
                  <pre class="text-xs bg-gray-100 p-2 rounded overflow-x-auto">{{
                      JSON.stringify(log.response, null, 2)
                    }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted} from 'vue';
import AppHeader from '@/components/AppHeader.vue';
import {
  addMockLogListener,
  getMockConfig,
  getMockStatus, removeMockLogListener, startMockServer,
  stopMockServer,
  updateMockConfig
} from '@/mock/mock-mes-server';

// 响应式状态
const serverStatus = reactive({
  running: false,
  port: 3000
});

const config = reactive({
  delay: 500,
  defaultResult: 'PASS',
  errorPattern: 'ERROR'
});

const logs = ref([]);
const isProcessing = ref(false);

// 启动服务器
const startServer = async () => {
  try {
    isProcessing.value = true;
    // 调用Electron API启动模拟服务器
    const result = startMockServer({
      port: serverStatus.port,
      config: config
    })

    if (result.success) {
      serverStatus.running = true;
      serverStatus.port = result.port;
    } else {
      alert(`启动服务器失败: ${result.error}`);
    }
  } catch (error) {
    console.error('启动服务器失败:', error);
    alert(`启动服务器失败: ${error.message || '未知错误'}`);
  } finally {
    isProcessing.value = false;
  }
};

// 停止服务器
const stopServer = async () => {
  try {
    isProcessing.value = true;
    // 调用Electron API停止模拟服务器
    const result = stopMockServer()

    if (result.success) {
      serverStatus.running = false;
    } else {
      alert(`停止服务器失败: ${result.error}`);
    }
  } catch (error) {
    console.error('停止服务器失败:', error);
    alert(`停止服务器失败: ${error.message || '未知错误'}`);
  } finally {
    isProcessing.value = false;
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    // 调用Electron API更新模拟服务器配置
    const result = updateMockConfig(config)

    if (result.success) {
      alert('配置已更新');
    } else {
      alert(`更新配置失败: ${result.error}`);
    }
  } catch (error) {
    console.error('更新配置失败:', error);
    alert(`更新配置失败: ${error.message || '未知错误'}`);
  }
};

// 清除日志
const clearLogs = () => {
  logs.value = [];
};

// 获取服务器状态
const getServerStatus = async () => {
  try {


    const status = getMockStatus()
    serverStatus.running = status.running;
    serverStatus.port = status.port;
  } catch (error) {
    console.error('获取服务器状态失败:', error);
  }
};

// 获取服务器配置
const getServerConfig = async () => {
  try {
    const serverConfig = getMockConfig()
    Object.assign(config, serverConfig);
  } catch (error) {
    console.error('获取服务器配置失败:', error);
  }
};

// 监听请求日志
const setupLogListener = () => {
  addMockLogListener((logData) => {
    logs.value.unshift({
      ...logData,
      timestamp: new Date().toLocaleString()
    });
  })
};

// 生命周期钩子
onMounted(async () => {
  await getServerStatus();
  await getServerConfig();
  setupLogListener();
});

onUnmounted(() => {
  // 移除事件监听器
  removeMockLogListener()
});
</script>